package com.newworld.dmsapp2.register;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.HouseManageListActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.bean.RelationType;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class RegisterHostActivity extends BaseActivity implements
		OnClickListener {
	private LinearLayout ly_intent;
	private Button btn_host_next;
	private Intent intent;
	private String houseId;
	private EditText hostNameEdtTxt;
	private EditText hostPhoneEdtTxt;
	private String ownername;
	private String ownerphone;

	// 户主id
	private String relationHostId = "";
	protected String response;
	protected String message = "登录失败";
	protected String flag, relationtype;
	private String sessionId;

	
	private View timeline_view_2;
	private ImageView timeline_3stage_image_3;
	private TextView timeline_text_3;
	private ProgressBar progressBar;
	protected List<RelationType> relationTypeList = new ArrayList<RelationType>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_register_host);
		initData();
		initViews();
		initEvents();

	}

	private void initData(){
		User user = SingleSample.getInstance(this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
	}
	@Override
	protected void initViews() {
		setTitlebarLeft(this, Config.TITLE_HOUSE_ATTATCH,
				HouseProvingActivity.class);
		ly_intent = (LinearLayout) findViewById(R.id.reg_host_intent);
		btn_host_next = (Button) findViewById(R.id.reg_host_btn);
		hostNameEdtTxt = (EditText) findViewById(R.id.reg_host_realname);
		hostPhoneEdtTxt = (EditText) findViewById(R.id.reg_host_mobile);
		timeline_view_2 = (View) findViewById(R.id.timeline_view_2);
		timeline_3stage_image_3 = (ImageView) findViewById(R.id.timeline_3stage_image_3);
		timeline_text_3 = (TextView) findViewById(R.id.timeline_text_3);
		progressBar = (ProgressBar) findViewById(R.id.proBar_get_data);
		if (UserMessageActivity.INTENT_FLAG == 1) {
			timeline_view_2.setVisibility(View.GONE);
			timeline_3stage_image_3.setVisibility(View.GONE);
			timeline_text_3.setVisibility(View.GONE);
			btn_host_next.setText("关联");
		}
		intent = getIntent();
		if (intent != null) {
			houseId = intent.getStringExtra("houseID");
			System.out.println("houseID" + houseId);
			// ownername = intent.getStringExtra("ownername");
			// ownerphone = intent.getStringExtra("ownerphone");
			// postscript = intent.getStringExtra("postscript");
		}
		getRelationType();
	}

	@Override
	protected void initEvents() {
		ly_intent.setOnClickListener(this);
		btn_host_next.setOnClickListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.reg_host_intent:
			Intent intent1 = new Intent(RegisterHostActivity.this,
					RegisterDishostActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("relationTypeList",
					(Serializable) relationTypeList);
			bundle.putString("houseID", houseId);
			intent1.putExtras(bundle);

			startActivity(intent1);
			break;
		case R.id.reg_host_btn:
			if (UserMessageActivity.INTENT_FLAG == 0) {
				hostRegisterIn();
			} else if (UserMessageActivity.INTENT_FLAG == 1)
				hostRelate();
			break;
		}

	}

	/**
	 * 户主关联
	 */
	private void hostRelate() {
		// TODO Auto-generated method stub
		ownername = hostNameEdtTxt.getText().toString();
		ownerphone = hostPhoneEdtTxt.getText().toString();
		if (ownername.length() == 0 || ownerphone.length() == 0) {
			showShortToast("用户名或手机号码不能为空");
		} else {

			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					if (Tool.isNetworkAvailable(RegisterHostActivity.this)) {
						progressBar.setVisibility(android.view.View.VISIBLE);
					} else {
						Toast.makeText(RegisterHostActivity.this, "请检查网络连接！",
								Toast.LENGTH_SHORT).show();
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if (Tool.isNetworkAvailable(RegisterHostActivity.this)) {
						try {
							Map<String, String> map = new HashMap<String, String>();
							map.put("functionCode", "houseRelateComplete");
							map.put("ownerPhone", ownerphone);
							map.put("ownerName", ownername);
							map.put("relationTypeCode", "owner");
							map.put("houseId", houseId);
							String setsessionid = "";
							User user = SingleSample.getInstance(RegisterHostActivity.this).getUser();
							if(null != user){
								if(null != user.getSessionId() && !user.getSessionId().equals("")){
									setsessionid = user.getSessionId();
								}
							}
							String result = HttpUtil.postRequestSe(Config.RELATE_URL, map,setsessionid);
							Log.e("户主关联result", result);

							message = new JSONObject(result)
									.getString("message");
							flag = new JSONObject(result).getString("flag");

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(RegisterHostActivity.this, message,
							Toast.LENGTH_SHORT).show();
					if (flag.equals("success")) {

						Intent intent = new Intent(RegisterHostActivity.this,
								HouseManageListActivity.class);
						startActivity(intent);
						finish();
					}

				}
			}.execute(null, null, null);
		}
	}

	/**
	 * 
	 * 户主点击注册
	 * 
	 * @param view
	 */
	private void hostRegisterIn() {

		ownername = hostNameEdtTxt.getText().toString();
		ownerphone = hostPhoneEdtTxt.getText().toString();
		if (ownername.length() == 0 || ownerphone.length() == 0) {
			showShortToast("用户名或手机号码不能为空");
		} else {

			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					if (Tool.isNetworkAvailable(RegisterHostActivity.this)) {
						progressBar.setVisibility(android.view.View.VISIBLE);
					} else {
						Toast.makeText(RegisterHostActivity.this, "请检查网络连接！",
								Toast.LENGTH_SHORT).show();
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if (Tool.isNetworkAvailable(RegisterHostActivity.this)) {
						try {

							if (relationTypeList != null
									&& relationTypeList.size() != 0) {
								for (RelationType relationType : relationTypeList) {
									if (relationType.getTypeCode().equals(
											"owner")) {
										relationHostId = relationType.getId();
									}
								}

							}
							Map<String, String> map = new HashMap<String, String>();
							map.put("ownerName", ownername);
							map.put("ownerPhone", ownerphone);
							map.put("houseId", houseId);
							map.put("relationTypeId", relationHostId);
							
							String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL, Config.CONFIRM_OWNERNAME)
									, map,sessionId);
							Log.e("户主信息验证result", result);

							message = new JSONObject(result)
									.getString("message");
							flag = new JSONObject(result).getString("flag");

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(RegisterHostActivity.this, message,
							Toast.LENGTH_SHORT).show();
					if (flag.equals("success")) {

						Intent intent = new Intent(RegisterHostActivity.this,
								UserMessageActivity.class);

						intent.putExtra("houseID", houseId);
						System.out.println("houseID" + houseId);
						intent.putExtra("ownername", ownername);
						intent.putExtra("ownerphone", ownerphone);
						intent.putExtra("relationtypeid", relationHostId);
						startActivity(intent);
						// finish();
					}

				}
			}.execute(null, null, null);
		}
	}

	private void getRelationType() {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String relationMessage;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(RegisterHostActivity.this)) {
					progressBar.setVisibility(android.view.View.VISIBLE);
				} else {
					Toast.makeText(RegisterHostActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(RegisterHostActivity.this)) {
					try {
						Map<String, String> map = new HashMap<String, String>();
						map.put("language", "");
						String result = HttpUtil.postRequestSe(Tool.getConfigUrl(Config.SERVER_URL, Config.GETRELASHIONSHIP_URL),
								 map,sessionId);
						Log.e("注册获取关系类型result", result);

						relationMessage = new JSONObject(result)
								.getString("message");
						if (new JSONObject(result).getString("flag").equals(
								"success")) {
							String rows = new JSONObject(result)
									.getString("rows");

							Type type = new TypeToken<List<RelationType>>() {
							}.getType();
							Gson gson = new Gson();
							relationTypeList = gson.fromJson(rows, type);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				progressBar.setVisibility(View.INVISIBLE);
				Toast.makeText(RegisterHostActivity.this, relationMessage,
						Toast.LENGTH_SHORT).show();

			}
		}.execute(null, null, null);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			Intent intent = new Intent(RegisterHostActivity.this,
					HouseProvingActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(intent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
